package com.liao.jta_jpa.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "userManagerFactory",
        basePackages = "com.liao.jta_jpa.dao.test")
public class UserDataSourceConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public LocalContainerEntityManagerFactoryBean userManagerFactory(EntityManagerFactoryBuilder builder){
        // 通过自动配置的EntityManagerFactoryBuilder创建
        // LocalContainerEntityManagerFactoryBean时
        // spring.jpa.hibernate.*配置的属性不会自动起作用
        // spring.jpa.*和spring.jpa.properties.*的属性会自动起作用
        return builder.dataSource(dataSource)
                // 设置实体类所在的包
                .packages("com.liao.jta_jpa.pojo.test")
                .persistenceUnit("userUnit")
                .build();
        // 如果配置文件中没指定properties.javax.persistence.transactionType，
        // 此处就需要通过如下代码来设置使用JTA全局事务
        // builder.build().setJpaPropertyMap(Map.of("javax.persistence.transactionType", "JTA"));
    }
}
